package org.grails.simplesolr

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.codehaus.groovy.grails.commons.GrailsApplication;

class SimpleSolrService {

	private SolrServer thisServer = null
	private SolrServer thisStreamingServer = null
	static transactional = false
	def grailsApplication
	
	def getServer() {
		if (thisServer == null) {
			GrailsApplication app = grailsApplication
			String url = (app.config.solr?.url)? app.config.solr.url : "http://localhost:8983/solr"
			thisServer = new CommonsHttpSolrServer(url)
		}
		return thisServer
	}

	def getStreamingUpdateServer(queueSize=20, numThreads=3) {
		if (thisStreamingServer == null) {
			GrailsApplication app = grailsApplication
			def url =  (app.config.solr?.url) ? app.config.solr.url : "http://localhost:8983/solr"
			thisStreamingServer = new StreamingUpdateSolrServer(url, queueSize, numThreads)
		}
		return thisStreamingServer
	}

	/**
	 * Execute a basic Solr query given a string formatted query
	 *
	 * @param query - the Solr query string
	 * @return Map with 'resultList' - list of Maps representing results and 'queryResponse' - Solrj query result
	 */
	def search(String query) {
		search( new SolrQuery( query ) )
	}

	/**
	 * Given SolrQuery object, execute Solr query
	 *
	 * @param solrQuery - SolrQuery object representating the query {@link http://lucene.apache.org/solr/api/org/apache/solr/client/solrj/SolrQuery.html}
	 * @return Map with 'resultList' - list of Maps representing results and 'queryResponse' - Solrj query result
	 */
	def search(SolrQuery solrQuery) {
		QueryResponse rsp = getServer().query( solrQuery );
		return new SimpleSolrQueryResponse(response:rsp);
	}
}
